<script setup>
import {ref, computed, watch, onMounted} from 'vue';
import _ from 'lodash';
import {$jui, $pageUtils} from '@jzl/utils'
import {useCommonStore} from "@jzl/stores";
import {DFT_ICONS} from "@jzl/icons";
import {$WinPageLowcode, $WinPages} from "@jzl/comps-mg";
// import mutil from '../utils/mutil';
import BuilderVars from "./builder-vars.vue";
import BuilderPropStyle from "./builder-prop-style.vue";

const emit = defineEmits(['submit', 'close', 'showCompMarket', 'showPageSetting'])
const props = defineProps(['currentPage', 'isRouterEnter', 'pageType']);
const store = useCommonStore();

// 数据
const pagePreviewShow = ref(false);
const logoImgError = ref(false);
const varShow = ref(false);

const pageSettingShow = ref(false);
const pageSettingWinName = ref('');
const pageSettingStepActive = ref('2');

const pageStyleWinName = ref("");
const pageStyleWinShow = ref(false);
const pageStyle = ref({});

const pageNameVisible = ref(false);
const pageCodeVisible = ref(false);

const pageWidth = ref(1920);
const pageHeight = ref(1080);

// 计算属性
const isH5 = computed(() => {
  return props.currentPage && props.currentPage.type == 2;
});

const pageSetting = computed(() => {
  return _.get(props.currentPage, "style.setting");
});

const varNum = computed(() => {
  let vars = _.get(props.currentPage, "vars");
  return vars ? vars.length : 0;
});

const isNotPageId = computed(() => {
  return !props.currentPage || !props.currentPage.page_id;
});

const projectLogo = computed(() => {
  return useCommonStore().project?.project_logo;
});

const projectName = computed(() => {
  return useCommonStore().project?.project_name;
});

const logoTextShow = computed(() => {
  return logoImgError.value || !projectLogo.value;
});

// 方法
function isEmptyPage(info) {
  return !info || !info.page_id;
}

function getPageTitle(page, dftTitle) {
  return _.get(page, "page_name") || dftTitle;
}

function backIndex() {
  emit('close');
  emit('cancel:win')
}

async function submit(autoSubmit = false) {
  emit('submit', autoSubmit);
}

async function preview() {
  if (props.currentPage && props.currentPage.page_id) {
    pagePreviewShow.value = true;
    return;
  }

  $jui.confirm(`页面未创建，请先保存页面！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await submit(true);
    pagePreviewShow.value = true;
  }).catch(() => {
  });
}

function handleShowCompMarket() {
  emit("showCompMarket");
}

function showPageSetting() {
  emit("showPageSetting");
}

function handleLowcodeChange(lowcode) {
  $bus.emit("global:lowcodeChange", lowcode);
}

function loadLogoError(e) {
  logoImgError.value = true;
}

function handleShowVars() {
  varShow.value = true;
}

function handlePageShowSetting() {
  let pageId = props.currentPage?.page_id
  if (!pageId) {
    $jui.toast("需先保存才能开发低码！");
    return;
  }

  $WinPageLowcode({
    show: true,
    pageId,
    isView: false,
    onConfirm: () => {}
  })
}

function handleShowPageWin() {
  $WinPages({
    onSelect: async (info) => {
      let type = _.get(info, "type");

      if (type == 3) {
        $jui.alert("定制页面不支持设计！");
        return false;
      }

      emit("changePage", info);
    }
  });
}

/*function handleShowPageSelectWin(pageType) {
  let gid = -1;

  $WinPages({
    defaultAppId: gid,
    onSelect: (page) => {
      let pageId = _.get(page, 'page_id');

      if (!pageId) return;

      if (pageType === "header") {
        props.currentPage.head_page_id = pageId;
        props.currentPage.header = page;
      } else if (pageType === "footer") {
        props.currentPage.foot_page_id = pageId;
        props.currentPage.footer = page;
      }
    }
  });
}*/

/*function handlePageRemove(pageType) {
  if (pageType === "header") {
    props.currentPage.head_page_id = -1;
    props.currentPage.header = null;
  } else if (pageType === "footer") {
    props.currentPage.foot_page_id = -1;
    props.currentPage.footer = null;
  }
}*/

/*function handleShowPagePreview(page, pageType) {
  if (!page || !page.page_id) {
    handleShowPageSelectWin(pageType);
    return;
  }

  $WinPagePreview({
    pageId: _.get(page, 'page_id'),
    pageCode: _.get(page, 'page_code')
  });
}*/

function initPageStyle() {
  if (!props.currentPage.style) {
    props.currentPage.style = {
      setting: {theme: ""},
      _ss: {}
    };
  }

  let pw = _.get(props.currentPage, 'style._ss.width');
  let ph = _.get(props.currentPage, 'style._ss.height');

  if (pw && pw > 0) pageWidth.value = pw;
  if (ph && ph > 0) pageHeight.value = ph;
}

function handleShowStyle() {
  initPageStyle();
  pageStyleWinShow.value = true;
  let styleMix = $putils.getInitMixStyle(_.cloneDeep(_.get(props.currentPage, 'style')));

  pageStyle.value = _.get(styleMix, "_ss");
}

onMounted(() => {
  initPageStyle();
});

watch(pageStyle, (val) => {
  if (props.currentPage && props.currentPage.style) {
    props.currentPage.style._ss = $pageUtils.clearDefaultStyleUnit(val);
  }
}, {deep: true});

watch(pageWidth, (val) => {
  if (val > 0 && props.pageType === 1) {
    props.currentPage.style._ss.width = val;
  }
});

watch(pageHeight, (val) => {
  if (val > 0 && props.pageType === 1) {
    props.currentPage.style._ss.height = val;
  }
});
</script>
<template>
  <div class="page-builder-header" ref="bheader">
    <div
      class="page-logo"
      :class="{ 'just-title': logoTextShow }"
      ref="logo">
      <img
        v-if="projectLogo"
        :src="projectLogo"
        @error="loadLogoError"
        v-tippy :content="projectName"
        :title="projectName"
      />
      <span v-text="projectName" class="art-font" />
    </div>
    <div class="actions">
      <div class="action-left">
        <div class="page-name-wrap">
          <JIcon
            :icon="DFT_ICONS.exchange"
            class="page-change-btn"
            v-tippy content="选择切换页面设计"
            @click="handleShowPageWin"
          />
          <el-popover
            v-model:visible="pageNameVisible"
            width="auto"
            placement="bottom"
            trigger="click"
          >
            <input
              v-if="pageNameVisible"
              size="small"
              placeholder="请输入页面名称"
              v-focus
              v-model="currentPage.page_name"
              class="page-name-input"
              @focus="$event.currentTarget.select()"
            />
            <template #reference>
              <span
                v-text="currentPage.page_name"
                class="page-name-label"
              />
            </template>
          </el-popover>
          <span class="color-gray-500 text-size-sm">/</span>

          <el-popover
            v-if="currentPage && !currentPage.page_id"
            v-model:visible="pageCodeVisible"
            width="auto"
            placement="bottom"
            trigger="click"
          >
            <input
              v-if="pageCodeVisible"
              size="small"
              placeholder="请输入页面编码"
              v-focus
              v-model="currentPage.page_code"
              class="page-name-input"
              @focus="$event.currentTarget.select()"
            />
            <template #reference>
              <span
                v-text="currentPage.page_code"
                class="page-name-label"
              />
            </template>
          </el-popover>
          <span v-else>{{ currentPage.page_code }}</span>
        </div>

        <el-dialog
          v-model="pagePreviewShow"
          :title="'页面预览：' + currentPage.page_name"
          custom-class="m-dialog-fullscreen"
          :close-on-click-modal="false"
          :append-to-body="true"
          :fullscreen="true">
          <div class="w-full h-full overflow-y-auto">
            <JzlPage
              v-if="pagePreviewShow"
              :page-id="currentPage.page_id"
              :class="{ 'page-h5-view': isH5 }"
            />
          </div>
        </el-dialog>

        <el-dialog
          v-model="varShow"
          title="页面变量管理"
          width="1100px"
          :fullscreen="false"
          class="m-dialog-style"
          :close-on-click-modal="false"
          :append-to-body="true">
          <BuilderVars
            v-model="currentPage.vars"
            trigger-page-type="page"
            label="页面变量"
          />
        </el-dialog>

        <el-drawer
          v-model="pageStyleWinShow"
          :title="pageStyleWinName"
          :append-to-body="true"
          :with-header="false"
          :size="360"
          direction="rtl"
          class="top-0"
        >
          <div class="elem-node-header">
            <div class="elem-node-tab justify-center">
              <JIcon :icon="DFT_ICONS.css" class="div"/>
              页面样式
            </div>
          </div>
          <div
            class="ele-design-prop relative w-full h-full"
          >
            <BuilderPropStyle
              v-if="pageStyle"
              class="h-full flex-1 overflow-y-auto border-t-0"
              v-model="pageStyle"
              :current-ele-data.sync="pageStyle"
            />
          </div>
        </el-drawer>
      </div>
      <div class="action-right">
        <el-input
          v-model="pageWidth"
          type="number"
          class="plain-input"
        >
          <template #prefix>宽</template>
        </el-input>
        <span style="color: #CCC;font-size: 10px;margin: 5px;">X</span>
        <el-input
          v-model="pageHeight"
          type="number"
          class="plain-input"
        >
          <template #prefix>高</template>
        </el-input>

        <JIcon
          :icon="DFT_ICONS.css"
          class="builder-btn builder-btn-icon"
          v-tippy content="页面样式"
          @click="handleShowStyle"
        />
        <el-badge
          :value="varNum"
          :hidden="!currentPage || !currentPage.vars || currentPage.vars.length <= 0"
        >
          <JIcon
            :icon="DFT_ICONS.var"
            class="builder-btn builder-btn-icon"
            v-tippy content="页面变量"
            @click="handleShowVars"
          />
        </el-badge>
        <JIcon
          :icon="DFT_ICONS.code"
          class="builder-btn builder-btn-icon jwdicon jwdicon-Code"
          :class="{ 'disabled': isNotPageId }"
          v-tippy content="低码开发"
          @click="handlePageShowSetting()"
        />

        <el-button type="success" round @click="preview()">预览</el-button>
        <el-button type="primary" round @click="submit(false)">保存</el-button>
        <el-button type="primary" plain round @click="backIndex()">关闭</el-button>
      </div>
    </div>
  </div>
</template>

